﻿using MebAppMarketplace.Biz;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MebAppMarketplace.Controllers
{
    /// <summary>
    /// 开发者后台，创建上传和管理自己的应用
    /// </summary>
    [Authorize(Roles = "Developer")]
    public class DeveloperController : Controller
    {
        public UserService userService { get; set; }
        public AppService appService { get; set; }
        public async Task<IActionResult> Index(string kw, int page = 1)
        {
            var list = appService.GetDeveloperApps(await userService.GetLoginUserIDAsync(), kw, page);
            return View(list);
        }

        public IActionResult AppJson(Guid id)
        {
            var m = appService.GetAppBase(id);
            var appInfo = new AppInfo();
            appInfo.AppID = id;
            appInfo.Publisher = m.Publisher;
            appInfo.Manufacturer = m.Manufacturer;
            appInfo.Name = m.Name;
            appInfo.Price = 1;
            appInfo.Description = m.Description;
            return View((object)JsonConvert.SerializeObject(appInfo, Formatting.Indented));
        }

        public IActionResult CreateApp()
        {
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> CreateApp(string name, string description)
        {
            if (string.IsNullOrEmpty(name))
            {
                ModelState.AddModelError("name", "名称不能为空");
            }
            else if (string.IsNullOrEmpty(description))
            {
                ModelState.AddModelError("desc", "描述不能为空");
            }
            else if (appService.IsAppNameExists(name))
            {
                ModelState.AddModelError("name", "同名应用已存在");
            }

            if (ModelState.IsValid)
            {
                await appService.CreateApp(name, description);
                return this.RedirectToReturnUrl();
            }
            return this.ViewError();
        }

        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(string username, string password)
        {
            var result = await userService.LoginUser(username, password);
            if (result == Model.LoginResult.登录成功)
            {
                return Redirect("/developer");
            }
            ModelState.AddModelError("", result.ToString());
            return this.ViewError();
        }



        public IActionResult Upload()
        {
            return View();
        }

        [HttpPost]
        [ActionName("Upload")]
        public async Task<IActionResult> UploadApp()
        {
            if (!Request.Form.Files.Any())
                ViewData["Message"] = "请选择要上传的文件";
            var file = Request.Form.Files[0];
            var tempFile = this.WriteAsTempFile(file);
            try
            {
                await appService.ExtractAppZip(tempFile);
                ViewData["Message"] = "上传成功！";
            }
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
            }
            return View("Upload");
        }
    }
}
